<?php
/**
 * Created by PhpStorm.
 * User: earl <guo@seosite.cn>
 * Date: 2017/7/28
 * Time: 上午10:52
 * Desc: 系统管理
 */

namespace Admin\Controller;

use Admin\Model\SystemModel;
use Home\Controller\ServerController;
use lyf\Tree;
use lyf\Upload;

class SystemController extends BaseController
{


    /**
     * @author Earl <guo@seosite.cn> from bayue.com
     * @desc 节点管理
     */
    public function nodes()
    {

        $u = $_SERVER['REQUEST_URI'];
        $url = substr($u, (strpos($u, '=') + 1), (strlen($u) - strpos($u, '=') - 6));
        $lis = explode('/', $url);
        $mmp['controller'] = $lis[2];
        $mmp['function'] = $lis[3];
        $res = M('nav')->where($mmp)->getField("id");
        $role_id = $_SESSION['adminster']['role_id'];
        if (!$role_id == 0) {
            $path = M('access')->where("role_id = " . $role_id)->getField("nav_id");
            $pathlist = explode('#', $path);
            if (!in_array($res, $pathlist)) {
                $this->error('没有权限!', U('Index/main'), 1);
                return false;
            }
        }

        $list = M('nav')->select();
        $obj = new Tree();
        $ret = $obj->array2tree($list, 'nav_title', 'id', 'pid', '0');
        $this->assign('list', $ret);
        $this->display();
    }

    /**
     * @author Earl <guo@seosite.cn> from bayue.com
     * @desc 添加节点
     */
    public function nodesAdd()
    {

        $pid = isset($_GET['pid']) ? $_GET['pid'] : 0;
        $this->assign('pid', $pid);

        if (IS_POST) {
            $data = I('post.');
            $data['type'] = 1;
            $ret = M('nav')->add($data);
            $ret ? $this->success('添加成功!', U('Admin/System/nodes')) : $this->error('添加失败！');
        }
        $list = M('nav')->select();
        $obj = new tree();
        $ret = $obj->array2tree($list, 'nav_title', 'id', 'pid', '0');
        $this->assign('list', $ret);
        $this->display();
    }

    /**
     * @author Earl <guo@seosite.cn> from bayue.com
     * @desc 编辑节点
     * @param $id
     */
    public function nodesEdit($id)
    {

        if (IS_POST) {
            $data = I('post.');
            $ret = M('nav')->where('id = ' . $id)->save($data);
            $ret ? $this->success('修改成功!') : $this->error('修改失败！');
        }
        $ret = M('nav')->find($id);
        $navList = M('nav')->select();
        $treeObj = new Tree();
        $nav_tree = $treeObj->array2tree($navList, 'nav_title', 'id', 'pid', '0');
        $this->assign('info', $ret);
        $this->assign('navList', $nav_tree);
        $this->display();
    }

    /**
     * @author Earl <guo@seosite.cn> from bayue.com
     * @desc 删除节点
     * @param $id
     */
    public function nodesDel($id)
    {

        $ret = M('nav')->delete($id);
        $ret ? $this->success('删除成功!') : $this->error('删除失败了哦！');
    }

    /**
     * @author Earl <guo@seosite.cn> from bayue.com
     * @desc 企业列表
     */
    public function enterprise()
    {

        $type = I('type', 1);
        //1 全部用户，2全部公司，3指定公司
        if ($type == 1) {
            $where = '1=1';
        } elseif ($type == 2) {
            $where['email'] = array('neq', '');
        } elseif ($type == 3) {
            $eid = I('eid');
            $where['enterprise_id'] = $eid;
        }
        $userObj = M('user');
        $count = $userObj->where($where)->count();
        $page = new \Think\Page($count, 10);
        $show = $page->show();
        $list = $userObj->where($where)->limit($page->firstRow . ',' . $page->listRows)
            ->order('application_time desc')
            ->select();

        $sysObj = new SystemModel();
        foreach ($list as &$v) {
            $v['email'] = empty($v['email']) ? $v['phone'] : $v['email'];
            $v['status_text'] = $sysObj->statusToTextIco($v['status']);
            $v['reg_time'] = date('Y/m/d', $v['application_time']);
            $v['status_change'] = empty($v['status']) ? '启用' : '禁用';
        }
        $enterprise_list = $this->enterpriseList();
        $enterprise_list[] = [
            'id' => 0,
            'username' => '全部'
        ];

        if (empty($eid)) $eid = 0;
        $this->assign(array(
            'eid' => $eid,
            'list' => $list,
            'enterprise_list' => $enterprise_list,
            'show' => $show
        ));
        $this->display('Enterprise/index');
    }

    /**
     * @desc 修改密码
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     * @param $id
     */
    public function change_pwd($id)
    {

        if (IS_POST) {
            $password = I('post.password');
            $new_pwd = md5($password);
            $ret = M('user')->where(array('id' => $id))->setField('password', $new_pwd);
            $ret ? $this->success('修改成功!') : $this->error('修改失败！');
        }
        $ret = M('user')->find($id);
        $this->assign('id', $id);
        $this->display('Enterprise/pwd');
    }

    /**
     * @desc 编辑企业
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     * @param $id
     */
    public function enterprise_edit($id)
    {

        if (IS_POST) {
            $data = I('post.');
            $id = $data['id'];
            $email_exit = M('user')->where(array('email' => array('eq', $data['email']), 'id' => array('neq', $id)))->find();
            if ($email_exit) $this->error('邮箱已使用，请更换！');
            $save_date = [
                'username' => $data['username'],
                'short_name' => $data['short_name'],
                'email' => $data['email'],
                'address' => $data['address'],
                'duty_name' => $data['duty_name'],
                'duty_position' => $data['duty_position'],
                'duty_phone' => $data['duty_phone'],
                'changeusernametime' => $data['changeusernametime'],
                'changeshort_nametime' => $data['changeshort_nametime']
            ];
            $ret = M('user')->where(array('id' => array('eq', $id)))->save($save_date);
            $ret ? $this->success('修改成功!') : $this->error('修改失败！');
        }
        $ret = M('user')->find($id);
        $this->assign('ret', $ret);
        if (empty($ret['phone'])) {
            $this->display('Enterprise/edit');
        } else {
            $enterpriseList = M('user')->where(array('email' => array('neq', 0)))->select();
            $this->assign('enterpriseList', $enterpriseList);
            $this->display('Enterprise/userinfo');
        }

    }

    /**
     * @desc 删除企业
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     * @param $id
     */
    public function enterprise_del($id)
    {

        $ret = M('user')->delete($id);
        $ret ? $this->success('删除成功!') : $this->error('删除失败了哦！');
    }

    /**
     * @desc 修改状态
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     * @param $id
     * @param $status
     */
    public function enterprise_status($id, $status)
    {

        $sta = $status == 1 ? 0 : 1;
        $ret = M('user')->where(array('id' => array('eq', $id)))->save(array('status' => $sta));
        $ret ? $this->success('修改成功!') : $this->error('修改失败了哦！');
    }

    public function role($id)
    {
        //判断是否有合法登录
        if (!$_SESSION['adminster']) {
            $this->error('非法请求！请先登录！', U('Admin/Login/index'), 2);
            return false;
        } else {
            $model = M('admin');
            $map['id'] = $_SESSION['adminster']['id'];
            $res = $model->where($map)->getField("ticket");
            if ($res != $_SESSION['adminster']['ticket']) {
                $this->error('账号已在他处登录！需要重新登录！', U('Admin/Login/index'), 2);
                return false;
            }
        }

        if (IS_POST) {
            $post_data = I('post.');
            $role = empty($post_data['role']) ? "" : implode(',', $post_data['role']);

            $uRet = M('web_role')->where(array('uid' => $post_data['id']))->find();
            if ($uRet) {
                $save_data = [
                    'role_name' => $role,
                    'update_time' => NOW_TIME
                ];
                $ret = M('web_role')->where(array('uid' => $post_data['id']))->save($save_data);
            } else {
                $add_data = [
                    'uid' => $post_data['id'],
                    'role_name' => $role,
                    'create_time' => NOW_TIME,
                    'update_time' => NOW_TIME
                ];
                $ret = M('web_role')->add($add_data);
            }
            if ($ret) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败了！');
            }
        }
        $arr = M('web_role')->where(array('uid' => $id))->getField('role_name');
        $arr = empty($arr) ? "" : explode(',', $arr);
        $this->assign(array(
            'uid' => $id,
            'arr' => $arr
        ));
        $this->display('Enterprise/role');
    }

    /**
     * @desc 首页视频
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function IndexVideo()
    {

        $videoObj = M('video');
        $count = $videoObj->where(array('status' => array('gt', 0)))->count();
        $page = new \Think\Page($count, 6);
        $show = $page->show();
        $list = $videoObj->field('video_id,video_img,video_url,add_time,status')->where(array('status' => array('gt', 0)))->limit($page->firstRow . ',' . $page->listRows)
            ->order('add_time desc')
            ->select();
        $sysObj = new SystemModel();
        foreach ($list as &$v) {
            $v['status_text'] = $sysObj->VideoStatusToTextIco($v['status']);
            $v['add_time'] = date('Y/m/d', $v['add_time']);
        }
        $this->assign(array(
            'list' => $list,
            'show' => $show
        ));
        $this->display('Indexvideo/index');
    }

    /**
     * @desc 删除视频
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     * @param $id
     */
    public function video_del($id)
    {

        $ret = M('video')->where(array('video_id' => $id))->delete();
        $ret ? $this->success('删除成功!') : $this->error('删除失败了哦！');
    }

    /**
     * @desc 通用上传文件
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function upload()
    {

        if (empty($_FILES)) {
            $this->error('没有文件上传');
        } else {
            $uploadObj = new Upload();
            $photo = $uploadObj->uploadOne($_FILES['file']);
            $photo['imgUrl'] = empty($photo) ? '' : C('site_url') . '/Uploads/photo/' . $photo['savepath'] . $photo['savename'];
            $this->success($photo);
        }
    }

    /**
     * @desc 编辑器图片上传，json返回
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function layUpload()
    {

        if (empty($_FILES)) {
            $data = array(
                'code' => 1,
                'msg' => '没有文件上传'
            );
        } else {
            $uploadObj = new Upload();
            $photo = $uploadObj->uploadOne($_FILES['file']);
            $photo['imgUrl'] = empty($photo) ? '' : C('site_url') . '/Uploads/photo/' . $photo['savepath'] . $photo['savename'];

            $data = array(
                'code' => 0,
                'msg' => '上传成功',
                'data' => array(
                    'src' => $photo['imgUrl'],
                    'title' => $photo['savename']
                )
            );
        }
        echo json_encode($data);
        exit();
    }


    /**
     * @desc 上传视频至网易云信
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function uploadVideo()
    {

        if (empty($_FILES)) {
            $this->error('没有文件上传');
        } else {
            $server_obj = new ServerController();
            $size = $_FILES['file']['size'];
            $fileName = $_FILES['file']['name'];
            $opt = [
                'trunkSize' => 2 * 1024 * 1024
            ];
            $files = [
                'size' => $size,
                'fileName' => $fileName,
                'tmp_name' => $_FILES['file']['tmp_name'],
                'filesize' => $_FILES['file']['size'],
                'offset' => 0//暂且为0
            ];
            $ret = $server_obj->uploadOne($opt, $files);
            $this->success($ret);
        }
    }

    /**
     * @desc 上传excel
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     * @return array|bool
     */
    public function uploadExcel()
    {

        $file_name = $_FILES['files']['tmp_name'];

        import("Org.Util.PHPExcel");   // 这里不能漏掉
        import("Org.Util.PHPExcel.IOFactory");
        $objReader = \PHPExcel_IOFactory::createReader('Excel5');
        $objPHPExcel = $objReader->load($file_name, $encode = 'utf-8');
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $highestColumn = $sheet->getHighestColumn(); // 取得总列数

        for ($i = 2; $i < $highestRow + 1; $i++) {
            $data['username'] = $objPHPExcel->getActiveSheet()->getCell('A' . $i)->getValue();
            $data['password'] = md5($objPHPExcel->getActiveSheet()->getCell('B' . $i)->getValue());
            $data['email'] = $objPHPExcel->getActiveSheet()->getCell('C' . $i)->getValue();
            $data['phone'] = $objPHPExcel->getActiveSheet()->getCell('D' . $i)->getValue();
            $data['status'] = $objPHPExcel->getActiveSheet()->getCell('E' . $i)->getValue();
            $data['type'] = $objPHPExcel->getActiveSheet()->getCell('F' . $i)->getValue();
            $data['enterprise_id'] = $objPHPExcel->getActiveSheet()->getCell('G' . $i)->getValue();
            $data['useravatar'] = $objPHPExcel->getActiveSheet()->getCell('H' . $i)->getValue();
            $data['address'] = $objPHPExcel->getActiveSheet()->getCell('I' . $i)->getValue();
            $data['short_name'] = $objPHPExcel->getActiveSheet()->getCell('J' . $i)->getValue();
            M('user')->add($data);
        }

        return $data;


//
//        $db = 'User';
//        import("Org.Util.PHPExcel");
//        $PHPExcel = new \PHPExcel();
//        $file = $_FILES['files']['tmp_name'];
//
//        $PHPReader = new \PHPExcel_Reader_Excel2007();
//        if (!$PHPReader->canRead($file)) {
//            $PHPReader = new \PHPExcel_Reader_Excel5();
//            if (!$PHPReader->canRead($file)){
//                return false;
//            }
//        }
//
//        $E = $PHPReader->load($file);
//        $cur = $E->getSheet(0);  // 读取第一个表
//        $end = $cur->getHighestColumn(); // 获得最大的列数
//        $line = $cur->getHighestRow(); // 获得最大总行数
//        // 获取数据数组
//        $info = array();
//        for ($row = 1; $row <= $line; $row ++) {
//            for ($column = 'A'; $column <= $end; $column ++) {
//                $val = $cur->getCellByColumnAndRow(ord($column) - 65, $row)->getValue();
//                $info[$row][] = $val;
//            }
//        }
//
//        $DB = M($db);
//        $data = array();
//        for ($i = 2; $i <= count($info); $i ++) {
//            for ($j = 0; $j < count($info[$i]); $j ++) {
//                for ($k = 0; $k < count($info[1]); $k ++) {
//                    $data[$i][$info[1][$k]] = $info[$i][$k];
//                }
//            }
//        }
//        $datalist = array_values($data);
//        $result = $DB->addAll($datalist);
//        // echo $DB->getLastSql();exit;
//        if ($result) {
//            return true;
//        }
        return false;
    }

    /**
     * @desc banner list
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function bannerList()
    {

        $videoObj = M('banner');
        $count = $videoObj->count();
        $page = new \Think\Page($count, 6);
        $show = $page->show();
        $list = $videoObj->order('number asc')->limit($page->firstRow . ',' . $page->listRows)
            ->select();
        $this->assign(array(
            'list' => $list,
            'show' => $show
        ));
        $this->display('Banner/index');
    }

    /**
     * @desc 添加banner
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function bannerAdd()
    {

        if (IS_POST) {
            $post_data = I('post.');
            $add_data = [
                'img' => $post_data['files'],
                'link' => $post_data['link'],
                'number' => $post_data['number'],
            ];

            $ret = M('banner')->add($add_data);
            if (empty($ret)) {
                $this->error('保存失败');
            } else {
                $this->success('保存成功');
            }
        }
        $this->display('Banner/add');
    }

    /**
     * @desc 编辑banner
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function bannerEdit()
    {

        if (IS_POST) {
            $post_data = I('post.');
            $id = $post_data['id'];
            $save_data = [
                'img' => $post_data['files'],
                'link' => $post_data['link'],
                'num' => $post_data['num']
            ];
            $ret = M('banner')->where(array('id' => $id))->save($save_data);
            if (empty($ret)) {
                $this->error('保存失败');
            } else {
                $this->success('保存成功');
            }
        }

        $ret = M('banner')->where(array('id' => $id))->find();
        $this->assign(array(
            'info' => $ret
        ));
        $this->display('Banner/edit');
    }

    /**
     * @desc 删除banner
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     * @param $id
     */
    public function bannerDel($id)
    {

        $ret = M('banner')->where('id = ' . $id)->delete();
        $ret ? $this->success('删除成功!') : $this->error('删除失败了哦！');
    }


    /**
     * @desc
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function enterpriseAdd()
    {

        if (IS_POST) {
            $email = $_POST['email'];

            $name = $_POST['username'];
            $accid = 'u_' . \lyf\Str::randString(30);
            $short_name = $_POST['short_name'];
            $address = $_POST['address'];
            $duty_name = $_POST['duty_name'];
            $duty_position = $_POST['duty_position'];
            $duty_phone = $_POST['duty_phone'];
            $password = $_POST['password'];

            //查询邮箱
            if ($email) {
                $enterprise = M('User')->where("email = '" . $email . "'")->find();
                if ($enterprise) {
                    $this->error('邮箱已存在');
                }
            }

            $data['email'] = $email;
            $data['username'] = $name;
            $data['accid'] = $accid;
            $data['short_name'] = $short_name;
            $data['duty_name'] = $duty_name;
            $data['duty_position'] = $duty_position;
            $data['duty_phone'] = $duty_phone;
            $data['address'] = $address;
            $data['password'] = md5($password);
            $data['application_time'] = time();
            $data['is_admin'] = 2;
            $data['status'] = 1;//0 未通过，1已通过，2已拒绝
            $data['type'] = 1;
            $data['useravatar'] = 'http://bayue-2017.oss-cn-hangzhou.aliyuncs.com/2017/zhongzhi/headsmall.png';
            M('User')->startTrans();
            $res = M('User')->add($data);
            if ($res) {
                M('User')->where('id = ' . $res)->setField('enterprise_id', $res);
                $enterpriseInfo['id'] = $res;
                $enterpriseInfo['email'] = $data['email'];
                $enterpriseInfo['username'] = $data['username'];
                $enterpriseInfo['accid'] = $data['accid'];
                $enterpriseInfo['short_name'] = $data['short_name'];
                $enterpriseInfo['duty_name'] = $data['duty_name'];
                $enterpriseInfo['duty_position'] = $data['duty_position'];
                $enterpriseInfo['duty_phone'] = $data['duty_phone'];
                $enterpriseInfo['enterprise_id'] = $res;
                $enterpriseInfo['token_type'] = '2';
                $homeObj = new \Home\Controller\BaseController();
                $token = $homeObj->_set_token($enterpriseInfo);
                //注册网易云用户；
                $netbeaObj = new ServerController();
                $name = $data['username'];
                $icon = $data['useravatar'];
                $im_token = explode('.', $token)[0];
                //这里面的token取.前
                $netbea_ret = (array)$netbeaObj->createUserId($data['accid'], $name, '{}', $icon, $im_token);
                if ($netbea_ret['code'] == 200) {
                    M('user')->commit();
                } else {
                    M('user')->rollback();
                    return showmessage('注册失败,', '', false);
                }
                $role_data = [
                    'uid' => $res,
                    'role_name' => 'video,direct,activity',
                    'create_time' => NOW_TIME
                ];
                M('web_role')->add($role_data);

                $this->success('注册成功');
            } else {
                $this->error('注册失败', '', false);
            }
        }

        $this->display('Enterprise/add');

    }

    /**
     * @desc 新增用户
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function userAdd()
    {

        if (IS_POST) {
            $username = $_POST['username'];
            $phone = $_POST['phone'];
            $password = md5($_POST['password']);
            $status = $_POST['status'];
            $is_admin = $_POST['is_admin'];
            $enterprise_id = $_POST['enterprise_id'];
            $username = !empty($username) ? $username : \lyf\Str::randString(rand(3, 9), 4);

            if (empty($enterprise_id)) {
                $type = 3;
            } else {
                $type = 2;
            }
            if ($phone) {
                $user = M('user')->where('phone = ' . $phone)->find();
                if ($user) {
                    $this->error('手机号已存在');
                }
            }

            $userinfo_reg['phone'] = $phone;
            $userinfo_reg['password'] = $password;
            $userinfo_reg['username'] = $username;
            $userinfo_reg['useravatar'] = 'http://bayue-2017.oss-cn-hangzhou.aliyuncs.com/2017/zhongzhi/headsmall.png';
            $userinfo_reg['enterprise_id'] = $enterprise_id;
            $userinfo_reg['role_id'] = '15';
            $accid = 'u_' . \lyf\Str::randString(30);
            $userinfo_reg['accid'] = $accid;
            $userinfo_reg['type'] = $type;
            $userinfo_reg['status'] = $status;//0 未通过，1已通过，2已拒绝
            $userinfo_reg['is_admin'] = $is_admin;//身份标识 0普通用户 1管理员 2企业账户
            $userinfo_reg['application_time'] = NOW_TIME;

            //开启事物
            M('user')->startTrans();
            $res = M('user')->add($userinfo_reg);
            if ($res) {
                $reged = M('user')->where($userinfo_reg)->find();
                $userinfo['id'] = $reged['id'];
                $userinfo['username'] = $reged['username'];
                $userinfo['phone'] = $reged['phone'];
                $userinfo['useravatar'] = $reged['useravatar'];
                $userinfo['enterprise_id'] = $reged['enterprise_id'];
                $userinfo['accid'] = $reged['accid'];
                $userinfo['type'] = $reged['type'];
                $userinfo['role_id'] = $reged['role_id'];
                $userinfo['is_admin'] = $reged['is_admin'];
                $userinfo['token_type'] = '1';
                $homeObj = new \Home\Controller\BaseController();
                $token = $homeObj->_set_token($userinfo);
                //注册网易云用户；
                $netbeaObj = new ServerController();
                $name = $reged['username'];
                $icon = $reged['useravatar'];
                $im_token = explode('.', $token)[0];
                //这里面的token取.前
                $netbea_ret = (array)$netbeaObj->createUserId($reged['accid'], $name, '{}', $icon, $im_token);
                if ($netbea_ret['code'] == 200) {
                    M('user')->commit();
                } else {
                    M('user')->rollback();
                    $this->error('新增失败');
                }

                $this->success('新增成功');
            } else {
                $this->error('新增失败');
            }
        }

        $enterpriseList = M('user')->where(array('email' => array('neq', 0)))->select();
        $this->assign('enterpriseList', $enterpriseList);
        $this->display('Enterprise/addUser');
    }

    /**
     * @desc 修改用户信息
     * @author Earl <guo@seosite.cn> .
     * @updateTime
     */
    public function updateUserInfo()
    {

        if (IS_POST) {
            $data = I('post.');
            $password = $data['password'];
            $id = $data['id'];
            $email_exit = M('user')->where(array('phone' => array('eq', $data['phone']), 'id' => array('neq', $id)))->find();
            if ($email_exit) $this->error('手机号已使用，请更换！');
            if (empty($password)) {
                $save_date = [
                    'username' => $data['username'],
                    'phone' => $data['phone'],
                    'address' => $data['address'],
                    'status' => $data['status'],
                    'is_admin' => $data['is_admin'],
                    'enterprise_id' => $data['enterprise_id']
                ];
            } else {
                $save_date = [
                    'username' => $data['username'],
                    'phone' => $data['phone'],
                    'address' => $data['address'],
                    'status' => $data['status'],
                    'is_admin' => $data['is_admin'],
                    'password' => md5($password),
                    'enterprise_id' => $data['enterprise_id']
                ];
            }

            $ret = M('user')->where(array('id' => array('eq', $id)))->save($save_date);
            $ret ? $this->success('修改成功!') : $this->error('修改失败！');
        }
    }
}